// pages/chef/activities/activities.js
const app = getApp()

Page({
  data: {
    familyActivities: [],
    showAddModal: false,
    showEditModal: false,
    showDetailModal: false,
    editingActivity: null,
    selectedActivity: null,
    newActivity: {
      title: '',
      description: '',
      planDate: '',
      planTime: '',
      icon: '🍽️',
      status: 'pending',
      priority: 'normal',
      participants: [],
      participantsText: ''
    },
    iconOptions: [
      '🍽️', '🎂', '🏃‍♂️', '🎊', '💝', '🛒', '📚', '🎬', '🎯', '🌟'
    ],
    statusOptions: [
      { value: 'pending', label: '待准备' },
      { value: 'in-progress', label: '准备中' },
      { value: 'completed', label: '已完成' },
      { value: 'cancelled', label: '已取消' }
    ],
    priorityOptions: [
      { value: 'normal', label: '普通' },
      { value: 'high', label: '重要' }
    ],
    // 计算属性
    statusIndex: 0,
    statusText: '待准备',
    priorityIndex: 0,
    priorityText: '普通',
    editStatusIndex: 0,
    editStatusText: '待准备',
    editPriorityIndex: 0,
    editPriorityText: '普通',
    // 筛选相关
    activeFilter: 'all',
    filteredActivities: [],
    totalActivities: 0,
    pendingActivities: 0,
    inProgressActivities: 0,
    completedActivities: 0,
    filterTextMap: {
      'pending': '待准备活动',
      'in-progress': '准备中活动',
      'completed': '已完成活动',
      'cancelled': '已取消活动'
    },
    // 页面滚动控制
    pageScrollDisabled: false
  },

  onLoad() {
    this.loadFamilyActivities()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadFamilyActivities()
  },

  // 加载家庭活动
  async loadFamilyActivities() {
    try {
      wx.showLoading({ title: '加载中...' })
      
      if (!app.globalData.familyInfo?._id) {
        wx.hideLoading()
        wx.showToast({ title: '未找到家庭信息', icon: 'error' })
        return
      }

      const { activityService } = require('../../../utils/cloud.js')
      const result = await activityService.getFamilyActivities(app.globalData.familyInfo._id)
      
      if (result.success && result.data) {
        // 为每个活动添加计算属性
        const activities = result.data.map(activity => ({
          ...activity,
          statusText: this.getStatusText(activity.status),
          // 确保participants是数组类型
          participants: Array.isArray(activity.participants) ? activity.participants : [],
          participantsText: Array.isArray(activity.participants) && activity.participants.length > 0 ? activity.participants.join('、') : ''
        }))
        
        this.setData({ familyActivities: activities })
        this.updateActivityStats()
        this.applyFilter()
        console.log('家庭活动加载完成，共', activities.length, '个活动')
      } else {
        console.log('加载家庭活动失败:', result.error)
        wx.showToast({ title: '加载失败', icon: 'error' })
      }
    } catch (error) {
      console.error('加载家庭活动时发生错误:', error)
      wx.showToast({ title: '加载失败', icon: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  // 显示添加活动弹窗
  showAddModal() {
    this.setData({
      showAddModal: true,
      newActivity: {
        title: '',
        description: '',
        planDate: '',
        planTime: '',
        icon: '🍽️',
        status: 'pending',
        priority: 'normal',
        participants: []
      }
    })
    this.updatePickerIndexes()
    // 禁止页面滚动
    this.disablePageScroll()
  },

  // 隐藏添加活动弹窗
  hideAddModal() {
    this.setData({ showAddModal: false })
    // 恢复页面滚动
    this.enablePageScroll()
  },

  // 显示编辑活动弹窗
  showEditModal(e) {
    const activity = e.currentTarget.dataset.activity
    console.log('准备编辑活动:', activity)
    
    // 确保participantsText有值
    const editingActivity = {
      ...activity,
      participantsText: Array.isArray(activity.participants) && activity.participants.length > 0 
        ? activity.participants.join('、') 
        : ''
    }
    
    this.setData({
      showEditModal: true,
      editingActivity: editingActivity
    })
    
    console.log('设置编辑活动数据:', this.data.editingActivity)
    this.updateEditPickerIndexes()
    // 禁止页面滚动
    this.disablePageScroll()
  },

  // 隐藏编辑活动弹窗
  hideEditModal() {
    this.setData({ showEditModal: false })
    // 恢复页面滚动
    this.enablePageScroll()
  },

  // 显示活动详情弹框
  showActivityDetail(e) {
    const activity = e.currentTarget.dataset.activity
    // 格式化创建时间
    const formattedActivity = {
      ...activity,
      createTime: this.formatCreateTime(activity.createTime)
    }
    
    this.setData({
      showDetailModal: true,
      selectedActivity: formattedActivity
    })
    // 禁止页面滚动
    this.disablePageScroll()
  },

  // 隐藏活动详情弹框
  hideDetailModal() {
    this.setData({ showDetailModal: false })
    // 恢复页面滚动
    this.enablePageScroll()
  },

  // 从详情弹框编辑活动
  editFromDetail() {
    this.hideDetailModal()
    this.showEditModal({ currentTarget: { dataset: { activity: this.data.selectedActivity } } })
  },

  // 格式化创建时间
  formatCreateTime(timeString) {
    if (!timeString) return '未知'
    
    try {
      const date = new Date(timeString)
      if (isNaN(date.getTime())) return '未知'
      
      const now = new Date()
      const diffTime = now.getTime() - date.getTime()
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 0) {
        return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      } else if (diffDays === 1) {
        return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      } else if (diffDays < 7) {
        return `${diffDays}天前 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
    } catch (error) {
      return '未知'
    }
  },

  // 更新选择器索引
  updatePickerIndexes() {
    const { newActivity, statusOptions, priorityOptions } = this.data
    const statusIndex = statusOptions.findIndex(s => s.value === newActivity.status)
    const priorityIndex = priorityOptions.findIndex(p => p.value === newActivity.priority)
    
    this.setData({
      statusIndex: statusIndex >= 0 ? statusIndex : 0,
      statusText: statusOptions[statusIndex]?.label || '待准备',
      priorityIndex: priorityIndex >= 0 ? priorityIndex : 0,
      priorityText: priorityOptions[priorityIndex]?.label || '普通'
    })
  },

  // 更新编辑选择器索引
  updateEditPickerIndexes() {
    const { editingActivity, statusOptions, priorityOptions } = this.data
    const statusIndex = statusOptions.findIndex(s => s.value === editingActivity.status)
    const priorityIndex = priorityOptions.findIndex(p => p.value === editingActivity.priority)
    
    this.setData({
      editStatusIndex: statusIndex >= 0 ? statusIndex : 0,
      editStatusText: statusOptions[statusIndex]?.label || '待准备',
      editPriorityIndex: priorityIndex >= 0 ? priorityIndex : 0,
      editPriorityText: priorityOptions[priorityIndex]?.label || '普通'
    })
  },

  // 输入活动标题
  onTitleInput(e) {
    this.setData({
      'newActivity.title': e.detail.value
    })
  },

  // 输入活动描述
  onDescriptionInput(e) {
    this.setData({
      'newActivity.description': e.detail.value
    })
  },

  // 选择活动日期
  onDateChange(e) {
    this.setData({
      'newActivity.planDate': e.detail.value
    })
  },

  // 选择活动时间
  onTimeChange(e) {
    this.setData({
      'newActivity.planTime': e.detail.value
    })
  },

  // 选择活动图标
  onIconChange(e) {
    this.setData({
      'newActivity.icon': e.currentTarget.dataset.icon
    })
  },

  // 选择活动状态
  onStatusChange(e) {
    const index = e.detail.value
    const status = this.data.statusOptions[index].value
    const label = this.data.statusOptions[index].label
    
    this.setData({
      'newActivity.status': status,
      statusIndex: index,
      statusText: label
    })
  },

  // 选择活动优先级
  onPriorityChange(e) {
    const index = e.detail.value
    const priority = this.data.priorityOptions[index].value
    const label = this.data.priorityOptions[index].label
    
    this.setData({
      'newActivity.priority': priority,
      priorityIndex: index,
      priorityText: label
    })
  },

  // 编辑活动状态变化
  onEditStatusChange(e) {
    const index = e.detail.value
    const status = this.data.statusOptions[index].value
    const label = this.data.statusOptions[index].label
    
    this.setData({
      'editingActivity.status': status,
      editStatusIndex: index,
      editStatusText: label
    })
  },

  // 编辑活动优先级变化
  onEditPriorityChange(e) {
    const index = e.detail.value
    const priority = this.data.priorityOptions[index].value
    const label = this.data.priorityOptions[index].label
    
    this.setData({
      'editingActivity.priority': priority,
      editPriorityIndex: index,
      editPriorityText: label
    })
  },

  // 输入参与人员
  onParticipantsInput(e) {
    const value = e.detail.value || ''
    console.log('参与人员输入原始值:', value)
    
    // 处理空字符串情况
    if (!value.trim()) {
      this.setData({
        'newActivity.participants': [],
        'newActivity.participantsText': ''
      })
      console.log('参与人员已清空')
      return
    }
    
    // 分割并过滤空值
    const participants = value.split('、')
      .map(p => p.trim())
      .filter(p => p.length > 0)
    
    this.setData({
      'newActivity.participants': participants,
      'newActivity.participantsText': value
    })
    
    console.log('参与人员输入:', value, '解析后:', participants)
  },

  // 编辑活动标题输入
  onEditTitleInput(e) {
    this.setData({
      'editingActivity.title': e.detail.value
    })
  },

  // 编辑活动描述输入
  onEditDescriptionInput(e) {
    this.setData({
      'editingActivity.description': e.detail.value
    })
  },

  // 编辑活动日期选择
  onEditDateChange(e) {
    this.setData({
      'editingActivity.planDate': e.detail.value
    })
  },

  // 编辑活动时间选择
  onEditTimeChange(e) {
    this.setData({
      'editingActivity.planTime': e.detail.value
    })
  },

  // 编辑活动图标选择
  onEditIconChange(e) {
    this.setData({
      'editingActivity.icon': e.currentTarget.dataset.icon
    })
  },

  // 编辑活动参与人员输入
  onEditParticipantsInput(e) {
    const value = e.detail.value || ''
    console.log('编辑参与人员输入原始值:', value)
    
    // 处理空字符串情况
    if (!value.trim()) {
      this.setData({
        'editingActivity.participants': [],
        'editingActivity.participantsText': ''
      })
      console.log('编辑参与人员已清空')
      return
    }
    
    // 分割并过滤空值
    const participants = value.split('、')
      .map(p => p.trim())
      .filter(p => p.length > 0)
    
    this.setData({
      'editingActivity.participants': participants,
      'editingActivity.participantsText': value
    })
    
    console.log('编辑参与人员输入:', value, '解析后:', participants)
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待准备',
      'in-progress': '准备中',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return statusMap[status] || '未知'
  },

  // 创建新活动
  async createActivity() {
    try {
      const { newActivity } = this.data
      
      if (!newActivity.title.trim()) {
        wx.showToast({ title: '请输入活动标题', icon: 'error' })
        return
      }

      if (!app.globalData.familyInfo?._id) {
        wx.showToast({ title: '未找到家庭信息', icon: 'error' })
        return
      }

      wx.showLoading({ title: '创建中...' })

      // 确保participants是数组类型
      const participants = Array.isArray(newActivity.participants) ? newActivity.participants : []
      
      const activityData = {
        ...newActivity,
        familyId: 'xiaoweichufang', // 指定为默认家庭ID
        planDateTime: newActivity.planDate + ' ' + newActivity.planTime,
        participants: participants
      }

      const { activityService } = require('../../../utils/cloud.js')
      const result = await activityService.createActivity(activityData)
      
      if (result.success) {
        wx.showToast({ title: '创建成功', icon: 'success' })
        this.hideAddModal()
        this.loadFamilyActivities()
        
        // 通知首页刷新数据
        if (app.globalData.eventBus) {
          app.globalData.eventBus.emit('familyActivitiesChanged')
        }
      } else {
        wx.showToast({ title: '创建失败', icon: 'error' })
      }
    } catch (error) {
      console.error('创建活动失败:', error)
      wx.showToast({ title: '创建失败', icon: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  // 更新活动
  async updateActivity() {
    try {
      const { editingActivity } = this.data
      console.log('开始更新活动，当前编辑数据:', editingActivity)
      
      if (!editingActivity.title.trim()) {
        wx.showToast({ title: '请输入活动标题', icon: 'error' })
        return
      }

      wx.showLoading({ title: '更新中...' })

      // 确保participants是数组类型
      const participants = Array.isArray(editingActivity.participants) ? editingActivity.participants : []
      
      const updateData = {
        title: editingActivity.title,
        description: editingActivity.description,
        planDate: editingActivity.planDate,
        planTime: editingActivity.planTime,
        icon: editingActivity.icon,
        status: editingActivity.status,
        priority: editingActivity.priority,
        participants: participants,
        planDateTime: editingActivity.planDate + ' ' + editingActivity.planTime
      }

      console.log('准备更新的数据:', updateData)
      console.log('活动ID:', editingActivity._id)

      const { activityService } = require('../../../utils/cloud.js')
      const result = await activityService.updateActivity(editingActivity._id, updateData)
      
      console.log('云数据库更新结果:', result)
      
      if (result.success) {
        wx.showToast({ title: '更新成功', icon: 'success' })
        this.hideEditModal()
        this.loadFamilyActivities()
        
        // 通知首页刷新数据
        if (app.globalData.eventBus) {
          app.globalData.eventBus.emit('familyActivitiesChanged')
        }
      } else {
        wx.showToast({ title: '更新失败', icon: 'error' })
      }
    } catch (error) {
      console.error('更新活动失败:', error)
      wx.showToast({ title: '更新失败', icon: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  // 删除活动
  async deleteActivity(e) {
    const activity = e.currentTarget.dataset.activity
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${activity.title}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...' })
            
            const { activityService } = require('../../../utils/cloud.js')
            const result = await activityService.deleteActivity(activity._id)
            
            if (result.success) {
              wx.showToast({ title: '删除成功', icon: 'success' })
              this.loadFamilyActivities()
              
              // 通知首页刷新数据
              if (app.globalData.eventBus) {
                app.globalData.eventBus.emit('familyActivitiesChanged')
              }
            } else {
              wx.showToast({ title: '删除失败', icon: 'error' })
            }
          } catch (error) {
            console.error('删除活动失败:', error)
            wx.showToast({ title: '删除失败', icon: 'error' })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 快速更新活动状态
  async quickUpdateStatus(e) {
    const { activity, status } = e.currentTarget.dataset
    
    try {
      wx.showLoading({ title: '更新中...' })
      
      const { activityService } = require('../../../utils/cloud.js')
      const result = await activityService.updateActivity(activity._id, { status })
      
      if (result.success) {
        wx.showToast({ title: '状态更新成功', icon: 'success' })
        this.loadFamilyActivities()
        
        // 通知首页刷新数据
        if (app.globalData.eventBus) {
          app.globalData.eventBus.emit('familyActivitiesChanged')
        }
      } else {
        wx.showToast({ title: '状态更新失败', icon: 'error' })
      }
    } catch (error) {
      console.error('更新活动状态失败:', error)
      wx.showToast({ title: '状态更新失败', icon: 'error' })
    } finally {
      wx.hideLoading()
    }
  },

  // 更新活动统计
  updateActivityStats() {
    const { familyActivities } = this.data
    const total = familyActivities.length
    const pending = familyActivities.filter(a => a.status === 'pending').length
    const inProgress = familyActivities.filter(a => a.status === 'in-progress').length
    const completed = familyActivities.filter(a => a.status === 'completed').length
    
    this.setData({
      totalActivities: total,
      pendingActivities: pending,
      inProgressActivities: inProgress,
      completedActivities: completed
    })
  },

  // 切换筛选
  toggleFilter(e) {
    const filter = e.currentTarget.dataset.filter
    this.setData({ activeFilter: filter })
    this.applyFilter()
  },

  // 应用筛选
  applyFilter() {
    const { familyActivities, activeFilter } = this.data
    let filtered = []
    
    if (activeFilter === 'all') {
      filtered = familyActivities
    } else {
      filtered = familyActivities.filter(activity => activity.status === activeFilter)
    }
    
    this.setData({ filteredActivities: filtered })
  },

  // 重置筛选
  resetFilter() {
    this.setData({ activeFilter: 'all' })
    this.applyFilter()
  },

  // 禁止页面滚动
  disablePageScroll() {
    // 设置页面不可滚动
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    // 添加禁止滚动的样式类
    this.setData({
      pageScrollDisabled: true
    })
  },

  // 恢复页面滚动
  enablePageScroll() {
    // 移除禁止滚动的样式类
    this.setData({
      pageScrollDisabled: false
    })
  }
}) 